<?php

namespace App\Console\Commands;

use App\Models\Order;
use App\Models\OrderLease;
use App\Models\ShopSms;
use App\Models\SmsRecord;
use App\Models\SmsTemplate;
use App\Services\OrderService;
use Illuminate\Console\Command;

class OverdueReminderCommand extends BaseCommand
{
    const LIMIT_NUM = 1;//一个月发送短信次数

    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'overdueReminder';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = '订单逾期短信提醒';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return int
     */
    protected function handleExec()
    {
        try {
            $where = [
                ['o.status',OrderService::ORDER_STATUS_OVERDUE],
            ];
            //数据
            $start_date = date('Y-m-01 00:00:00', strtotime(date('Y-m')));
            $end_date = date('Y-m-d 23:59:59', strtotime("$start_date +1 month -1 day"));
            $where1[] = ['create_time','>=',$start_date];
            $where1[] = ['create_time','<=',$end_date];
            $where1[] = ['template_id',SmsTemplate::SMS_TEMPLATE_ORDER_OVERDUE];
            $countpluck = SmsRecord::where($where1)->distinct('order_id')->pluck('order_id');
            $data = obToArray(Order::from('sp_order_2 as o')
                ->select('o.seller_id','o.id','o.trade_no','m.mobile')
                ->leftjoin('sp_member_2 as m','o.uid','m.id')
                ->where($where)
                ->whereNotIn('o.trade_no',$countpluck)
                ->orderBy('o.id', 'desc')
                ->get());

            foreach ($data as $item){
                $where1 = [];
                $where1[] = ['create_time','>=',$start_date];
                $where1[] = ['create_time','<=',$end_date];
                $where1[] = ['template_id',SmsTemplate::SMS_TEMPLATE_ORDER_OVERDUE];
                $where1[] = ['order_id',$item['trade_no']];
                $count = SmsRecord::where($where1)->count('id');
                if($count > self::LIMIT_NUM){
                    continue;
                }else{
                    $overdue_amount = OrderLease::where(['order_id'=>$item['id'],'status'=>OrderLease::ORDER_LEASE_STATUS_OVERDUE])->sum('rent');
                    if($overdue_amount > 0){
                        //发送短信
                        $res = ShopSms::overdueReminder($item['seller_id'],$item['mobile'],$overdue_amount,$item['trade_no']);
//                   dd($res);
                    }
                }
            }
            $this->infoLog('订单逾期短信提醒执行成功',$data);
        }catch (\Exception $exception){
            $this->infoLog('订单逾期短信提醒执行失败'.$exception->getMessage());
        }
    }
}
